package com.fxnotes;

import com.fxnotes.common.ui.Controller;
import com.fxnotes.common.ui.ModuleController;
import com.fxnotes.common.ui.NavigationPath;
import com.fxnotes.common.ui.NavigationPathBuilder;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javafx.beans.property.Property;
import javafx.scene.Node;
import javafx.scene.Parent;

@Singleton
public class AppController extends Controller<ModuleController> {
    
    private final MainDialog mainDialog;
    
    @Inject
    public AppController(MainDialog mainDialog) {
        super(Resources.APP_CONTROLLER);
        this.mainDialog = mainDialog;
    }
    
    @Inject
    public void setModules(Set<ModuleController> modules) {
        for (ModuleController moduleController : modules) {
            addController(moduleController);
        }
    }
    
    public void init() {
        initTabs();
        selectTab();        
    }
    
    private void initTabs() {
        Map<String, Property<? extends Node>> tabs = new HashMap<>();
        for (Map.Entry<String, ModuleController> controllerEntry : controllers.entrySet()) {
            String controllerName = controllerEntry.getKey();
            ModuleController controller = controllerEntry.getValue();
            tabs.put(controllerName, controller.getProperty());
        }
        
        mainDialog.addTabs(tabs);
    }
    
    private void selectTab() {
        showPath(NavigationPathBuilder
                .create()
                .append(Resources.MODULE_BOOKS)
                .append(Resources.PRESENTER_BOOKS)
                .build());
    }
    
    public Parent getNode() {
        return mainDialog.getNode();
    }
    
    @Override
    public void showPath(NavigationPath path) {
        if (isValidPath(path)) {
            super.showPath(path);
            
        } else {
            System.out.println(String.format("Path %s is invalid!!!", path));
        }
    }
    
    @Override
    protected void onControllerChanged(Controller module) {
        mainDialog.selectTab(module.getName());
    }
}
